package cn.wolfcode.wolfcodemall.controller.fore;

import cn.wolfcode.wolfcodemall.domain.Address;
import cn.wolfcode.wolfcodemall.domain.User;
import cn.wolfcode.wolfcodemall.service.AddressService;
import cn.wolfcode.wolfcodemall.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 注册相关请求
 */
@Controller
public class RegisterController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private UserService userService;
    //注册页面
    @RequestMapping("/register")
    public String registerPage(Model model){
        //查询所有的省份信息
        List<Address> addressList = addressService.findRoot();
        //根据省份id查询市级信息
        List<Address> cityList = addressService.findList(addressList.get(0).getAddressAreaid());
        //根据市的id查询县区信息
        List<Address> districtList = addressService.findList(cityList.get(0).getAddressAreaid());

        model.addAttribute("addressList",addressList);
        model.addAttribute("cityList",cityList);
        model.addAttribute("districtList",districtList);
        return "/fore/register";
    }

    //当地址信息发生变化时
    @RequestMapping(value = {"/address/{addressId}", "/tmall/address/{addressId}"},produces = "application/json;charset=utf-8")
    @ResponseBody
    public String changeAddress(@PathVariable String addressId){
        //查询addressId下的地址信息
        List<Address> addressList = addressService.findList(addressId);

        JSONObject jsonObject = new JSONObject();
        if(addressList.size() <= 0){ //查询地址失败
            jsonObject.put("success",false);
            return jsonObject.toJSONString();
        }
        //查询可能有的子地址信息
        List<Address> childAddressList = addressService.findList(addressList.get(0).getAddressAreaid());

        //查询地址成功
        jsonObject.put("success",true);
        jsonObject.put("addressList",addressList);
        jsonObject.put("childAddressList",childAddressList);

        return jsonObject.toJSONString();
    }

    //注册功能
    @RequestMapping("/doRegister")
    public String doRegister(User user){
        //将获取的数据保存到数据库
        userService.save(user);
        //跳转登录页面
        return "redirect:/login";
    }
}
